#include "Graphics.h"

//Loads Graphics resources
Graphics::Graphics(){
	rWindow = SDL_CreateWindow("Amora", (wWidth / 2), (wHeight / 2), wWidth, wHeight, SDL_WINDOW_SHOWN);

	if(rWindow == NULL)
		std::cout << SDL_GetError() << std::endl;

	r = SDL_CreateRenderer(rWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

	if(r == NULL)
		std::cout << SDL_GetError() << std::endl;

	textures["test"] = loadSurface("gfx/test.png");
}

SDL_Texture *Graphics::loadSurface(const char *path){
	SDL_Surface *tmp = IMG_Load(path);

	SDL_Texture *optimized = NULL;
	if(tmp != NULL){
		optimized = SDL_CreateTextureFromSurface(r, tmp);

		SDL_FreeSurface(tmp);
	}else{
		std::cout << SDL_GetError() << std::endl;
	}

	return optimized;
}

SDL_Texture *Graphics::getTexture(const char* txt){
	itr = textures.find(txt);

	if(itr != textures.end())
		return itr->second;
	else
		return NULL;
}

bool Graphics::freeTexture(SDL_Texture *texture){
	if(texture != NULL){
		SDL_DestroyTexture(texture);

		return true;
	}

	return false;
}

//X & Y = Relative to Screen, Texture = Image to be drawn, Rect clip = Relative part of spritesheet to be drawn
void Graphics::drawSurface(int x, int y, SDL_Texture *texture, const SDL_Rect &clip) const {
	SDL_Rect offset;

	offset.x = x;
	offset.y = y;
	offset.w = clip.w;
	offset.h = clip.h;

	SDL_RenderClear(r);

	SDL_RenderCopy(r, texture, &clip, &offset);

	SDL_RenderPresent(r);
}

//Cleans up graphic resources
Graphics::~Graphics(){
	SDL_DestroyTexture(textures["test"]);
	SDL_DestroyRenderer(r);
	SDL_DestroyWindow(rWindow);
}